package com.example.javaee.Util.sensitiveWordFilter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.javaee.exception.CourseAdminException;
import org.apache.commons.lang3.CharUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    private static final String REPLACEMENT = "***";

    private TrieNode rootNode = new TrieNode();


    /**
     * 初始化前缀树
     */
    @PostConstruct        //@PostConstruct修饰的方法会在服务器加载Servle的时候运行，并且只会被服务器执行一次。PostConstruct在构造函数之后执行
    private void init() throws CourseAdminException
    {
        try(
                InputStream ins = this.getClass().getClassLoader().getResourceAsStream("SensitiveWordList.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
        )
        {
            String keyWord;
            while ((keyWord = reader.readLine()) != null)
            {
                this.addKeyWord(keyWord);
            }
            logger.info("load sensitive wordlist success!");
        }
        catch (IOException e)
        {
            logger.error("load sensitive wordlist error: "+e.getMessage());
        }
    }

    /**
     * 将一个敏感词加入到前缀树中
     * @param keyWord
     */
    private void addKeyWord(String keyWord)
    {
        logger.info("当前单词" + keyWord);
        logger.info("单词长度" + keyWord.length());
        TrieNode tempNode = rootNode;
        int st = 0;
        // 格式兼容，UTF-8+BOM读入的第一个字符为65279
        if(((int)keyWord.charAt(0)) == 65279)
        {
            st = 1;
        }
        for(int i=st;i<keyWord.length();i++)
        {
            char c = keyWord.charAt(i);
        //    int num = (int)c;
        //    logger.info("当前字符" + c);
        //    logger.info("当前字符号码" + num);
            TrieNode subNode = tempNode.getSubNode(c);

            if(subNode == null){
                //初始化子节点
                subNode = new TrieNode();
                tempNode.addSubNode(c,subNode);
            }
            //指向子节点，进入下一轮循环
            tempNode = subNode;
            //设置结束标识
            if(i == keyWord.length() - 1){
                logger.info("设置标志成功");
                subNode.setKeywordEnd(true);
            }
        }
    }

    /**
     * 对文本中的敏感词进行过滤
     * @param text 待过滤的敏感词
     * @return 过滤之后的敏感词
     */
    public String filter(String text) throws CourseAdminException
    {
        try
        {
            if(StringUtils.isBlank(text)){
                return null;
            }
            TrieNode tempNode = rootNode;
            int begin = 0;
            int position = 0;
            StringBuilder sb = new StringBuilder();
            while (position < text.length()){
                char c = text.charAt(position);

                //跳过符号
                if(isSymbol(c)){
                    //若指针1处于根节点，将此符号计入结果，让指针2向后走一步
                    if(tempNode == rootNode){
                        begin++;
                        sb.append(c);
                    }
                    //无论符号在开头或中间，指针3都向后走一步
                    position++;
                    continue;
                }
                //检查下级节点
                tempNode = tempNode.getSubNode(c);
           //     logger.info("当前字符：" + c);
                if(tempNode == null){
                    //以begin开头的字符串不是敏感词
                    sb.append(text.charAt(begin));
                    //进入下一个位置
                    position = ++begin;
                    //重新指向根节点
                    tempNode = rootNode;
                }else if (tempNode.isKeywordEnd()){
            //        logger.info("下级结点标志 ： " + tempNode.isKeywordEnd());
                    //发现敏感词，将begin~position字符串替换掉
                    sb.append(REPLACEMENT);
                    //向后继续判断
                    begin = ++position;
                    //重新指向根节点
                    tempNode = rootNode;
                }else {
                    //检查下一个字符
                    position++;
                }
            }
            //将最后一批字符计入结果
            sb.append(text.substring(begin));
            return sb.toString();
        }
        catch (Exception e)
        {
            throw new CourseAdminException(
                    "过滤评论敏感词失败!");
        }
    }

    /**
     * 判断该字符是否是符号
     * @param c
     * @return
     */
    private boolean isSymbol(Character c)
    {
        //0x2E80~0x9FFF 是东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }



}